package com.platform.modules.wallet.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.platform.common.aspectj.IgnoreAuth;
import com.platform.common.constant.AppConstants;
import com.platform.common.enums.YesOrNoEnum;
import com.platform.common.shiro.ShiroUtils;
import com.platform.common.shiro.utils.Md5Utils;
import com.platform.common.utils.redis.RedisUtils;
import com.platform.common.version.ApiVersion;
import com.platform.common.version.VersionEnum;
import com.platform.common.web.domain.AjaxResult;
import com.platform.modules.chat.domain.ChatGroup;
import com.platform.modules.chat.domain.ChatGroupMonitor;
import com.platform.modules.chat.domain.ChatUser;
import com.platform.modules.chat.domain.ChatUserMonitor;
import com.platform.modules.chat.service.ChatGroupMonitorService;
import com.platform.modules.chat.service.ChatGroupService;
import com.platform.modules.chat.service.ChatUserMonitorService;
import com.platform.modules.chat.service.ChatUserService;
import com.platform.modules.wallet.domain.ChatTestMsg;
import com.platform.modules.wallet.domain.Wallet;
import com.platform.modules.wallet.domain.WalletAccount;
import com.platform.modules.wallet.enums.AccountTypeEnum;
import com.platform.modules.wallet.service.*;
import com.platform.modules.wallet.vo.PasswordInitVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 测试推送消息
 */
@Controller
@Slf4j
@RequestMapping("/test")
public class TestRespController {

    @Autowired
    private RedisUtils redisUtils;
    @Resource
    private WalletKPayService walletKPayService;
    @Resource
    private ChatGroupMonitorService groupMonitorService;
    @Resource
    private ChatGroupService groupService;
    @Resource
    private WalletTransferService transferService;
    @Resource
    private WalletRedPacketSubService redPacketSubService;
    @Resource
    private ChatUserService userService;
    @Resource
    private WalletAccountService accountService;
    @Resource
    private WalletDailyBillhService billhService;
    @Resource
    private WalletService walletService;
    @Resource
    private WalletRechargeCashService rechargeCashService;
    @Resource
    private ChatUserService chatUserService;

    /**
     * 获取一条测试推送消息
     */
    @IgnoreAuth
    @GetMapping("/testLogin")
    public void testLogin(@RequestParam String walletCode, HttpServletResponse response) throws IOException {

        response.sendRedirect(walletKPayService.login(walletCode));
    }

    private static String getParam(Map<String, Object> params) {
        StringBuilder s1 = new StringBuilder();
        for (String key : params.keySet()) {
            s1.append(key).append("=").append(params.get(key)).append("&");
        }
        return s1.toString();
    }

    @IgnoreAuth
    @GetMapping("/getabc")
    @ResponseBody
    public AjaxResult getabc() {

        Dict dict = new Dict();
        List<ChatGroupMonitor> chatGroupMonitors = groupMonitorService.queryList(new ChatGroupMonitor());
        for (ChatGroupMonitor chatGroupMonitor : chatGroupMonitors) {
            ChatGroup byId = groupService.getById(chatGroupMonitor.getGroupId());
            if (ObjectUtil.isNotEmpty(byId)) {
                dict.put(byId.getName(), chatGroupMonitor.getProfit() + ":" + chatGroupMonitor.getDown() + ":" + chatGroupMonitor.getUp());
            }
        }

        String total = redisUtils.get(AppConstants.WALLET_TOTAL);
        dict.put("total", total);


        Integer transfer = transferService.querySumAll();
        dict.put("t", transfer);
        Integer redpacketSub = redPacketSubService.querySumAll();
        dict.put("r", redpacketSub);

        Integer rechargeToday = rechargeCashService.getRechargeToday();
        dict.put("t11",rechargeToday);
        dict.put("t12",rechargeCashService.getCashToday());
        dict.put("all11",rechargeCashService.getRechargeAll());
        dict.put("all12",rechargeCashService.getCashAll());

        dict.put("regall",chatUserService.queryCount(new ChatUser()));

//        testTotal();
//        jiance();
//        record();

        return AjaxResult.success(dict);
    }

    @IgnoreAuth
    @ResponseBody
    @PostMapping("/initPassword")
    public AjaxResult initPassword() {

        Long userId = 1589178093233299458l;
        // 当前用户
        ChatUser cu = userService.findById(userId);
        String s = RandomUtil.randomNumbers(6);
        String payPassword = Md5Utils.credentials(Md5Utils.md5(s), cu.getSalt());
        cu.setPassword(payPassword);
        userService.updateById(cu);

        return AjaxResult.success("成功:" + s);
    }

    private void testTotal() {
        List<ChatUser> chatUsers = userService.queryList(new ChatUser());
        for (ChatUser chatUser : chatUsers) {
            Integer acc = accountService.queryTodaySum(chatUser.getUserId());
            Integer bill = billhService.querySum(chatUser.getUserId());
            Integer total = acc + bill;
            Wallet wallet = walletService.getById(chatUser.getUserId());
            wallet.setBalance(total);
            walletService.update(wallet);
            if (total.intValue() < 0) {
                log.error("发现余额为负值的用户 {}:{}", chatUser.getPhone(), total);
            } else if (total.intValue() != 0) {
                log.info("手机号：{} 金额：{}", chatUser.getPhone(), total);
            }
        }
        System.out.println("结束");
    }

    /**
     * 检测负数
     */
    private void jiance() {
        ChatUser chatUser = userService.queryByPhone("13900000510");
        if (ObjectUtil.isEmpty(chatUser)) {
            log.info("空");
            return;
        }
        log.info("开始监测");
        while (true) {
            int balance = walletService.getBalance(chatUser.getUserId());
            if (balance < 0) {
                log.info("出现负数：{}", balance);
            }
        }
    }

    private void record() {
        Long userId = 1602564794610823170l;

        List<WalletAccount> walletAccounts = accountService.queryList(new WalletAccount().setUserId(userId));
        int balance = 0;
        for (WalletAccount walletAccount : walletAccounts) {
            balance = walletAccount.getAmount() + balance;
            AccountTypeEnum type = walletAccount.getType();
//            String typeName="";
//            if (AccountTypeEnum.RECHARGE.equals(type)){
//                typeName="充值";
//            } else if (AccountTypeEnum.CASH.equals(type)) {
//                typeName="提现";
//            }else if (AccountTypeEnum.TRANSFER_IN.equals(type)) {
//                typeName="接收转账";
//            }else if (AccountTypeEnum.TRANSFER_OUT.equals(type)) {
//                typeName="转出转账";
//            }else if (AccountTypeEnum.RED_PACKET_IN.equals(type)) {
//                typeName=type.getInfo();
//            }else if (AccountTypeEnum.REFUND.equals(type)) {
//                typeName="";
//            }else if (AccountTypeEnum.CASH.equals(type)) {
//                typeName="提现";
//            }
            String format = StrUtil.format("{} 金额:{} 余额:{} 时间:{}",
                    walletAccount.getType().getInfo(),
                    walletAccount.getAmount(),
                    balance,
                    DateUtil.format(walletAccount.getCreateTime(), "HH:mm:ss"));
            System.out.println(format);
        }
    }
}
